<?php

namespace app\index\controller;

use app\model\Domain;
use app\model\DomainInfo;
use app\model\DomainVisit;
use think\facade\Cache;
use think\facade\Session;
use think\facade\Validate;
use think\facade\View;
use think\validate\ValidateRule;
use UserHub\Client;

class Index extends Common
{
    /**
     * 显示资源列表.
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        $gotoMainDomain = '';
        if ($this->request->host() != get_system_config('main_domain')) {
            $gotoMainDomain = get_system_config('main_domain');
            
        }

        $user_uid = Session::get('user_uid');

        $code = $this->request->param('code');

        $login_client = new Client([
            'host' => get_system_config('user_hub_host'),
            'key' => get_system_config('user_hub_key'),
            'secret' => get_system_config('user_hub_secret'),
        ]);
        if (!empty($code)) {
            $user_info = $login_client->getUserinfoByCode($code);

            $user_uid = $user_info['uid'];
            Session::set('user_uid', $user_uid);
        }
        $login_url = $login_client->getBowserRedirectUrl((string) url('Index/index')->domain(true));

        $list_domain = Domain::where('user_uid', $user_uid)->select();

        $list_domain_info = DomainInfo::where('user_uid', $user_uid)->select();

        $domain_count = Cache::get('domain_count');

        if (is_null($domain_count)) {
            $domain_count = Domain::count();
            Cache::set('domain_count', $domain_count, 60);
        }

        $domain_visit_count = Cache::get('domain_visit_count');

        if (is_null($domain_visit_count)) {
            $domain_visit_count = DomainVisit::count();
            Cache::set('domain_visit_count', $domain_visit_count, 60);
        }

        $model_domain_info = null;

        $domain_info_id = $this->request->param('domain_info_id');

        if (!empty($domain_info_id)) {
            $model_domain_info = DomainInfo::find($domain_info_id);
        }

        View::assign('model_domain_info', $model_domain_info);

        View::assign('list_domain', $list_domain);
        View::assign('list_domain_info', $list_domain_info);
        View::assign('domain_visit_count', $domain_visit_count);
        View::assign('domain_count', $domain_count);
        View::assign('login_url', $login_url);
        View::assign('user_uid', $user_uid);
        View::assign('gotoMainDomain', $gotoMainDomain);

        return View::fetch();
    }

    public function logout()
    {
        Session::clear();

        return $this->success('退出成功', 'index');
    }

    public function saveDomain()
    {
        $post_data = $this->request->post();

        if (isset($post_data['domain'])) {
            $post_data['domain'] = $post_data['domain'];
        }

        $validate = Validate::rule('domain|域名', ValidateRule::isRequire())
            ->rule('user_uid|用户UID', ValidateRule::isRequire());

        if (!$validate->check($post_data)) {
            return $this->error($validate->getError());
        }

        $model_domain = Domain::where('domain', $post_data['domain'])->find();

        if (!empty($model_domain)) {
            return $this->error('域名已存在');
        }

        Domain::create($post_data);
        Cache::delete('domain_visit_count');

        return $this->success('添加成功', 'index');
    }

    public function saveDomainInfo()
    {
        $post_data = $this->request->post();

        $validate = Validate::rule('domain|域名', ValidateRule::isRequire())
        ->rule('user_uid|用户UID', ValidateRule::isRequire())
        ->rule('title|名称', ValidateRule::isRequire())
        ->rule('beian|备案', ValidateRule::isRequire())
        ->rule('beian_name|备案名称', ValidateRule::isRequire());

        if (!$validate->check($post_data)) {
            return $this->error($validate->getError());
        }

        $post_data['domain'] = trim($post_data['domain']);

        $id = $this->request->param('id');
        $model_domain = null;
        if (!empty($id)) {
            unset($post_data['id']);
            $model_domain = DomainInfo::find($id);
        }

        if (empty($model_domain)) {
            $model_domain = DomainInfo::where('domain', $post_data['domain'])
            ->where('id', '<>', $id)
            ->find();

            if (!empty($model_domain)) {
                return $this->error('域名已存在');
            }
            $model_domain = new DomainInfo();
        } else {
            $user_uid = Session::get('user_uid');
            if ($model_domain->user_uid != $user_uid) {
                return $this->error('提交错误');
            }
        }

        $model_domain->save($post_data);

        return $this->success('提交成功', 'index');
    }

    public function deleteDomain($id)
    {
        Domain::destroy($id);
        Cache::delete('domain_visit_count');

        return json_message();
    }

    public function deleteDomainInfo($id)
    {
        DomainInfo::destroy($id);

        return json_message();
    }

    public function visitDomain()
    {
        $domain = Domain::order('last_scan_time asc')
            ->find();

        $domain->last_scan_time = time();
        $domain->scan_times++;
        $domain->save();

        return json_message($domain);
    }
}
